import { useEffect, useState, useCallback, useMemo, useRef } from "react";
import i18n from "i18n-js";
import { toJS } from "mobx";
import Taro from "@tarojs/taro";
import PageContainer from "@/components/PageContainer";
import { DynamicColors, GStyleSheet, GDynamicValue } from "@/utils/DarkMode";
import { View, Text } from "@tarojs/components";
import { GButton } from "@/components/GButton";
import CheckBox from "@/components/CheckBox";
import DashedTitle from '@/components/DashedTitle';
import Toast from "@/utils/Toast";
import { networkConfigTypes } from '@/config/product';
import configWifiModel from '../models/configWifi';
import { getConfigModeByNetworkType, getConfigModelName, needUserCheckStep } from '../models/configTool';
import Tips from './Tips';


const dstyles = GStyleSheet.create({
  page: {
    backgroundColor: DynamicColors.normalBackgroundColor,
  },
  container: {
    width: "100%",
    height: "100%",
    padding: "32rpx",
    boxSizing: "border-box",
    borderTop: "1rpx solid rgba(0,0,0,0.1)",
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between'
  },
  desc: {
    width: "100%",
    padding: "20rpx 40rpx",
    boxSizing: "border-box",
    backgroundColor: "#fafafa",
    borderRadius: 10,
    flex: 1,
    flexDirection: 'column',
  },
  tabs: {
    justifyContent: 'space-around',
    marginTop: 10,
    width: "100%",
  },
  tab: {
    flexDirection: 'column',
  },
  noActive: {
    color: new GDynamicValue('#999', '#585858'),
  },
  active: {
    color: new GDynamicValue('#333', '#fff'),
  },
  activePoint: {
    backgroundColor: new GDynamicValue('#333', '#fff'),
  },
  point: {
    width: 5,
    height: 5,
    backgroundColor: '#000',
    borderRadius: 8,
    marginTop: 6,
  },
  checkView: {
    marginTop: 20,
    marginBottom: 20,
  },
  checkText: {
    marginLeft: 10,
    color: DynamicColors.normalTextColor
  }
});


const AddTipPage = () => {

  const styles = dstyles.useDynamicStyle();
  const [index, setIndex] = useState(0);
  const [check, setCheck] = useState(false);

  const configModels = useMemo(() => {
    console.log('configWifiModel', configWifiModel);
    if (configWifiModel.productConfig) {
      const productConfig = toJS(configWifiModel.productConfig);
      const data = productConfig.networkConfigType.map(i => {
        console.log('getConfigModeByNetworkType', i);
        return getConfigModeByNetworkType({ type: i, config: productConfig });
      }).filter(i => !!i);

      const hasBle = data.find(i => i.type === networkConfigTypes.TNetworkConfigTypeBTWifi);
      const hasSoftAp = data.find(i => i.type === networkConfigTypes.TNetworkConfigTypeSoftAp);
      if (hasBle && hasSoftAp) {
        // 同时拥有ble 和 ap，只保留ap
        return [hasSoftAp];
      }
      return data;
    } else {
      return [];
    }
  }, [])

  console.log('configModels', configModels);

  const curConfigModel = useMemo(() => {
    return configModels[index];
  }, [index, configModels]);

  const needCheck = useMemo(() => {
    return needUserCheckStep(curConfigModel!);
  }, [curConfigModel])

  const tabs = useMemo(() => {
    return (
      <View className='centerFlex' style={styles.tabs}>
        {configModels.map((item, i) => {
          const name = getConfigModelName(item!);
          const isSelected = index == i;
          return (<View
            style={styles.tab}
            className='centerFlex'
            key={item!.type}
            onClick={() => setIndex(i)}
          >
            <Text
              style={
                !isSelected ? { ...styles.noActive } : { ...styles.active }
              }
            >
              {name}
            </Text>
            <View
              style={{
                ...styles.point,
                ...isSelected
                  ? { ...styles.activePoint }
                  : { backgroundColor: '#0000' },
              }}
            />
          </View>);
        })}
      </View >
    )
  }, [configModels, index, styles]);

  const userCheckFinishStep = useMemo(() => {
    return needCheck ? (
      <View className='centerFlex' style={styles.checkView}>
        <CheckBox checked={check} onPress={() => { setCheck(!check) }} />
        <Text style={styles.checkText}>{i18n.t('FINISH_EVETHING')}</Text>
      </View>
    ) : <View style={styles.checkView} />;
  }, [needCheck, styles, check])

  const onConfirm = useCallback(() => {
    if (needCheck && !check) {
      Toast.info(i18n.t('CHECK_FINISH_EVETHING'));
      return;
    }
    configWifiModel.updateConfigModelAndGo(curConfigModel!);
  }, [needCheck, check, curConfigModel]);

  const haveGoPage = useRef(false);
  const pageShow = useRef(true);

  const getSSID = useCallback(() => {
    console.log('getSSID', pageShow.current);
    if (curConfigModel!.type === networkConfigTypes.TNetworkConfigTypeSoftAp) {
      Taro.getConnectedWifi({
        success: (res) => {
          if (res.wifi && res.wifi.SSID && res.wifi.SSID.includes(curConfigModel!.productConfig.softAPSSIDPrefix!)) {
            if (!haveGoPage.current) {
              // 需要限制，不然会多次跳转
              haveGoPage.current = true;
              configWifiModel.updateConfigModelAndGo(curConfigModel!);
            }
          } else {
            console.log('获取连接wifi失败', res);
          }
        },
        complete: (res) => {
          console.log('获取连接wifi complete', res);
        }
      })
    }
  }, [curConfigModel]);

  useEffect(() => {
    // 监听 Wi-Fi 变化
    if (curConfigModel!.type !== networkConfigTypes.TNetworkConfigTypeSoftAp) {
      Taro.offWifiConnected(() => { });
    } else {
      Taro.onWifiConnected((res) => {
        console.log('onWifiConnected');
        if (pageShow.current) {
          getSSID();
        }
      });
    }
  }, [getSSID, curConfigModel]);

  const getSSIDRef = useRef(getSSID);
  useEffect(() => {
    getSSIDRef.current = getSSID;
  }, [getSSID]);

  useEffect(() => {
    haveGoPage.current = false;
    pageShow.current = true;
    Taro.onAppShow((res) => {
      if (pageShow.current) {
        console.log('onAppShow', res);
        if (getSSIDRef.current) {
          getSSIDRef.current();
        }
      }
    })
    Taro.startWifi({
      complete: (res) => {
        console.log('startWifi', res);
      }
    });
    return () => {
      Taro.stopWifi();
      pageShow.current = false;
    }
  }, []);

  const haveNext = curConfigModel!.type !== networkConfigTypes.TNetworkConfigTypeSoftAp;

  return (
    <PageContainer title={i18n.t('ADD_DEVICE')} style={styles.page}>
      <View style={styles.container}>
        <DashedTitle title={i18n.t('CONFIG_NETWORK')} num={2} isDashed />
        <View style={styles.desc} className='centerFlex'>
          {tabs}
          {/* <Tips model={curConfigModel!} /> */}
          {curConfigModel!.type !== networkConfigTypes.TNetworkConfigTypeSoftAp && <Tips model={curConfigModel!} />}
          {curConfigModel!.type !== networkConfigTypes.TNetworkConfigTypeBTWifi && <Tips model={curConfigModel!} />}
        </View>
        {haveNext && userCheckFinishStep}
        {haveNext && <GButton text={i18n.t('NEXT')} onPress={onConfirm} />}
      </View>
    </PageContainer>
  );
};

export default AddTipPage;
